<script>
import {mapState} from "vuex";

export default {
  name: "roleDialog",
  props: {
    /* 父组件传递过来的prop用于控制组件的显示和隐藏 */
    showRoleDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      /*角色列表数组 */
      roleList: [],
      /* 员工分配角色带给服务器的参数 */
      roleParams: {
        id: '',
        roleIds: []
      }
    }
  },
  methods: {
    /* fetchRoleList()函数用于派发action获取所有角色列表 */
    async fetchRoleList() {
      try {
        const roleList = await this.$store.dispatch('employeesStore/fetchRoleList')
        this.roleList = roleList
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    /* fetchRoleIds()函数用于派发action根据用户ID获取该用户的角色ID数组  */
    async findRoleIds(id) {
      try {
        const {roleIds} = await this.$store.dispatch('employeesStore/findUserDetail', id)
        this.roleParams.id = id
        this.roleParams.roleIds = roleIds
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    /* 对话框关闭时的回调函数 */
    handleClose() {
      this.$emit('update:showRoleDialog', false)
    },
    /* 点击取消按钮的回调函数 */
    handleCancel() {
      this.$emit('update:showRoleDialog', false)
    },
    /* 点击确定按钮时的回调函数 */
    async handleSubmit() {
      try {
        const message = await this.$store.dispatch('employeesStore/assignRoles', this.roleParams)
        this.$message.success(message)
        this.$emit('update:showRoleDialog', false)
      } catch (error) {
        this.$message.error(error.message)
      }
    }
  },
  computed: {},
  mounted() {
    /*fetchRoleList()获取所有角色列表的action
    * this.fetchRoleList()
    *  */
  }
}
</script>

<template>
  <el-dialog v-bind="$attrs" title="员工分配角色" :visible="showRoleDialog" @close="handleCancel">
    <el-checkbox-group v-model="roleParams.roleIds">
      <el-checkbox v-for="(item,index) in roleList" :label="item.id" :key="item.id">{{ item.name }}</el-checkbox>
    </el-checkbox-group>
    <span slot="footer" class="dialog-footer">
      <el-button type="danger" @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<style scoped lang="scss">

</style>
